package ewms.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.toolkit.SqlHelper;
import ewms.bo.EwmsTransferWarehouseAddBo;
import ewms.bo.EwmsTransferWarehouseEditBo;
import ewms.bo.EwmsTransferWarehouseQueryBo;
import ewms.domain.EwmsTransferWarehouseDetail;
import ewms.domain.EwmsWasteInventory;
import ewms.mapper.EwmsTransferWarehouseDetailMapper;
import ewms.mapper.EwmsWasteInventoryMapper;
import ewms.utils.EwmsUtils;
import ewms.vo.transfer_warehouse.EwmsTransferWarehouseDetailVo;
import ewms.vo.transfer_warehouse.EwmsTransferWarehouseTempForPage;
import ewms.vo.transfer_warehouse.EwmsTransferWarehouseWrapperVo;
import ewms.common.exception.CustomException;
import ewms.common.utils.PageUtils;
import ewms.common.core.page.PagePlus;
import ewms.common.core.page.TableDataInfo;
import ewms.service.IEwmsTransferWarehouseService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import ewms.domain.EwmsTransferWarehouse;
import ewms.mapper.EwmsTransferWarehouseMapper;
import ewms.vo.transfer_warehouse.EwmsTransferWarehouseVo;
import org.springframework.transaction.annotation.Transactional;

import javax.validation.constraints.NotEmpty;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 危废转库Service业务层处理
 *
 * @author zhaoxiaochun
 * @date 2022-02-15
 */
@Service
public class EwmsTransferWarehouseServiceImpl extends ServiceImpl<EwmsTransferWarehouseMapper, EwmsTransferWarehouse> implements IEwmsTransferWarehouseService {

	@Autowired
	private EwmsWasteInventoryMapper wasteInventoryMapper;
	@Autowired
	private EwmsTransferWarehouseDetailMapper transferWarehouseDetailMapper;

	@Override
	public EwmsTransferWarehouseVo queryById(Long transferWarehouseId) {
		return getVoById(transferWarehouseId, EwmsTransferWarehouseVo.class);
	}

	@Override
	public TableDataInfo<EwmsTransferWarehouseWrapperVo> selectPageTransferWarehouseList(EwmsTransferWarehouseQueryBo bo) {
		// 1. 分页查询库存信息记录
		Page<EwmsTransferWarehouseTempForPage> tempForPage = baseMapper.selectPageTransferWarehouseTempForPageList(PageUtils.buildPage(), bo);
		Page<EwmsTransferWarehouseWrapperVo> transferWarehouseWrapperVoPage = new Page<>(tempForPage.getCurrent(), tempForPage.getSize(), tempForPage.getTotal());
		List<EwmsTransferWarehouseTempForPage> tempForPageRecords = tempForPage.getRecords();
		if (!tempForPageRecords.isEmpty()) {
			// 2.取到库存信息记录的id，批量查询转库记录
			List<Long> wasteInventoryIdList = tempForPageRecords.stream().map(temObj -> temObj.getWasteInventoryId()).collect(Collectors.toList());
			EwmsTransferWarehouseQueryBo tempBo = new EwmsTransferWarehouseQueryBo();
			tempBo.setWasteInventoryIdList(wasteInventoryIdList);
			List<EwmsTransferWarehouseDetailVo> transferWarehouseDetailVoList = baseMapper.selectTransferWarehouseList(tempBo);
			List<EwmsTransferWarehouseWrapperVo> resultList = buildTransferWrapperVoList(transferWarehouseDetailVoList);
			transferWarehouseWrapperVoPage.setRecords(resultList);
		}
		return PageUtils.buildDataInfo(transferWarehouseWrapperVoPage);
	}

	@Override
	public List<EwmsTransferWarehouseWrapperVo> selectTransferWarehouseList(EwmsTransferWarehouseQueryBo bo) {
		List<EwmsTransferWarehouseDetailVo> detailVoList = baseMapper.selectTransferWarehouseList(bo);
		return buildTransferWrapperVoList(detailVoList);
	}

	/**
	 * 构造结构型数据
	 *
	 * @param transferWarehouseDetailVoList
	 * @return
	 */
	private List<EwmsTransferWarehouseWrapperVo> buildTransferWrapperVoList(List<EwmsTransferWarehouseDetailVo> transferWarehouseDetailVoList) {
		Map<EwmsTransferWarehouseWrapperVo, List<EwmsTransferWarehouseWrapperVo.EwmsTransferWarehouseDetailWrapperVo>> map = new HashMap<>();
		for (EwmsTransferWarehouseDetailVo transferWarehouseDetailVo : transferWarehouseDetailVoList) {
			EwmsTransferWarehouseWrapperVo.EwmsTransferWarehouseDetailWrapperVo TransferDetailWrapperVo = BeanUtil.toBean(transferWarehouseDetailVo, EwmsTransferWarehouseWrapperVo.EwmsTransferWarehouseDetailWrapperVo.class);
			EwmsTransferWarehouseWrapperVo TransferWrapperVo = BeanUtil.toBean(transferWarehouseDetailVo, EwmsTransferWarehouseWrapperVo.class);
			List<EwmsTransferWarehouseWrapperVo.EwmsTransferWarehouseDetailWrapperVo> detailWrapperVoList = map.get(TransferWrapperVo);
			if (Objects.isNull(detailWrapperVoList)) {
				detailWrapperVoList = new ArrayList<>();
				detailWrapperVoList.add(TransferDetailWrapperVo);
				map.put(TransferWrapperVo, detailWrapperVoList);
			} else {
				detailWrapperVoList.add(TransferDetailWrapperVo);
			}
		}

		List<EwmsTransferWarehouseWrapperVo> transferWarehouseWrapperVoList = new ArrayList<>();
		for (Map.Entry<EwmsTransferWarehouseWrapperVo, List<EwmsTransferWarehouseWrapperVo.EwmsTransferWarehouseDetailWrapperVo>> entry : map.entrySet()) {
			EwmsTransferWarehouseWrapperVo transferWrapperVo = entry.getKey();
			transferWrapperVo.setTransferWarehouseDetailList(entry.getValue());
			transferWarehouseWrapperVoList.add(transferWrapperVo);
		}
		List<EwmsTransferWarehouseWrapperVo> resultList = transferWarehouseWrapperVoList.stream().sorted(EwmsTransferWarehouseWrapperVo::compareTo).collect(Collectors.toList());
		return resultList;
	}

	@Override
	public TableDataInfo<EwmsTransferWarehouseVo> queryPageList(EwmsTransferWarehouseQueryBo bo) {
		PagePlus<EwmsTransferWarehouse, EwmsTransferWarehouseVo> result = pageVo(PageUtils.buildPagePlus(), buildQueryWrapper(bo), EwmsTransferWarehouseVo.class);
		return PageUtils.buildDataInfo(result);
	}

	@Override
	public List<EwmsTransferWarehouseVo> queryList(EwmsTransferWarehouseQueryBo bo) {
		return listVo(buildQueryWrapper(bo), EwmsTransferWarehouseVo.class);
	}

	private LambdaQueryWrapper<EwmsTransferWarehouse> buildQueryWrapper(EwmsTransferWarehouseQueryBo bo) {
		Map<String, Object> params = bo.getParams();
		LambdaQueryWrapper<EwmsTransferWarehouse> lqw = Wrappers.lambdaQuery();
		lqw.eq(bo.getToWarehouseId() != null, EwmsTransferWarehouse::getToWarehouseId, bo.getToWarehouseId());
		lqw.eq(bo.getTransferDate() != null, EwmsTransferWarehouse::getTransferDate, bo.getTransferDate());
		return lqw;
	}

	@Override
	@Transactional(rollbackFor = Exception.class)
	public Boolean insertByAddBo(EwmsTransferWarehouseAddBo bo) {
		boolean saveFlag = false;
		// 保存主表信息
		EwmsTransferWarehouse add = BeanUtil.toBean(bo, EwmsTransferWarehouse.class);
		add.setTransferDate(EwmsUtils.handleSelectDate(add.getTransferDate()));
		validEntityBeforeSave(add);
		saveFlag = save(add);

		// 保存转库明细表信息
		@NotEmpty(message = "危废转库明细信息不能为空") List<EwmsTransferWarehouseDetail> transferWarehouseDetailList = bo.getTransferWarehouseDetailList();
		for (EwmsTransferWarehouseDetail ewmsTransferWarehouseDetail : transferWarehouseDetailList) {
			EwmsWasteInventory ewmsWasteInventory = wasteInventoryMapper.selectById(ewmsTransferWarehouseDetail.getWasteInventoryId());
			if (Objects.isNull(ewmsWasteInventory)) {
				throw new CustomException("库存信息未找到.");
			}
			// 转库明细信息保存
			EwmsTransferWarehouseDetail addDetail = new EwmsTransferWarehouseDetail();
			addDetail
				.setCreateTime(bo.getCreateTime())
				.setCreateBy(bo.getCreateBy())
				.setTransferWarehouseId(add.getTransferWarehouseId())
				.setWasteInventoryId(ewmsWasteInventory.getWasteInventoryId())
				.setFromWarehouseId(ewmsWasteInventory.getWarehouseId());
			saveFlag = saveFlag && SqlHelper.retBool(transferWarehouseDetailMapper.insert(addDetail));

			// 更新库存表中仓库信息(只有在还未转过库 或者 转过库且当前转库时间大于等于最后一次转库时间时，才修改库存表中的仓库信息)
			Date maxTransferDate = baseMapper.selectMaxTransferDate(ewmsWasteInventory.getWasteInventoryId());
			if (Objects.isNull(maxTransferDate) || maxTransferDate.compareTo(add.getTransferDate()) <= 0) {
				EwmsWasteInventory updateWasteInventory = new EwmsWasteInventory();
				updateWasteInventory
					.setWasteInventoryId(ewmsWasteInventory.getWasteInventoryId())
					.setWarehouseId(add.getToWarehouseId())
					.setUpdateBy(add.getCreateBy())
					.setUpdateTime(add.getCreateTime());
				wasteInventoryMapper.updateById(updateWasteInventory);
			}
		}
		return saveFlag;
	}

	@Override
	public Boolean updateByEditBo(EwmsTransferWarehouseEditBo bo) {
		EwmsTransferWarehouse update = BeanUtil.toBean(bo, EwmsTransferWarehouse.class);
		validEntityBeforeSave(update);
		return updateById(update);
	}

	/**
	 * 保存前的数据校验
	 *
	 * @param entity 实体类数据
	 */
	private void validEntityBeforeSave(EwmsTransferWarehouse entity) {
		//TODO 做一些数据校验,如唯一约束
	}

	@Override
	public Boolean deleteWithValidByIds(Collection<Long> ids, Boolean isValid) {
		if (isValid) {
			//TODO 做一些业务上的校验,判断是否需要校验
		}
		return removeByIds(ids);
	}
}
